def debug(data):
    pass
import socket
import simplejson
import io
END = '\r\n'
encode = simplejson.encoder.JSONEncoder().encode


class Client(object):
    version = 'Orbit 1.0'
    def __init__(self, addr="localhost", port=9000):
        self.addr = addr
        self.port = port
        self.socket = None
        self.id = 0
        
    def connect(self):
        if self.socket:
            debug("Already Connected")
            return
        self.socket = io.client_socket(self.addr, self.port)
        self.socket.setblocking(1)
#        self.sendline(self.version)

    def disconnect(self):
        self.socket.close()
        self.socket = None
        
    def reconnect(self):
        self.disconnect()
        self.connect()
        
    def sendline(self, line=""):
        self.socket.send('%s%s' % (line, END))
    
    def msg(self, data):
        return "<script>window.parent.event(%s);</script>" % encode(data)

    
    def event(self, recipients, body, json=True):
        if json:
            body = self.msg(body)
        if not self.socket:
            raise "ConnectionLost"
        try:
            self.id += 1
            self.sendline(self.version)
            self.sendline('Event')
            self.sendline('id: %s' % self.id)
            for recipient in recipients:
                self.sendline('recipient: %s' % (str(recipient)))
            self.sendline('length: %s' % len(body))
            self.sendline()
            self.socket.send(body)
            return self.read_response()
        except socket.error:
            self.disconnect()
            raise "ConnectionLost"
    def read_response(self):
        return self.socket.recv(1000)
